import { initComponents } from './components/index.js';
import { initHeader } from './components/header.js';

// 显示操作结果提示
function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.textContent = message;
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.classList.add('show');
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(toast);
            }, 300);
        }, 2000);
    }, 100);
}

// 当DOM加载完成时初始化
document.addEventListener('DOMContentLoaded', async function() {
    try {
        // 首先初始化所有组件
        await initComponents();
        
        // 初始化头部组件
        initHeader();
        
        // 获取DOM元素
        const jsonModal = document.getElementById('jsonModal');
        const imageModal = document.getElementById('imageModal');
        const jsonTool = document.getElementById('jsonTool');
        const imageTool = document.getElementById('imageTool');
        const closeButtons = document.querySelectorAll('.close-btn');
        const dropZone = document.getElementById('dropZone');
        const imageInput = document.getElementById('imageInput');
        const imagePreview = document.getElementById('imagePreview');
        const base64Output = document.getElementById('base64Output');
        const selectImageBtn = document.getElementById('selectImage');
        const copyBase64Btn = document.getElementById('copyBase64');
        const previewContainer = document.getElementById('previewContainer');

        // 确保所有必需的元素都存在
        if (!jsonModal || !imageModal || !jsonTool || !imageTool || !closeButtons.length || 
            !dropZone || !imageInput || !imagePreview || !base64Output || !selectImageBtn || 
            !copyBase64Btn || !previewContainer) {
            throw new Error('某些DOM元素未找到');
        }

        // 初始化显示状态
        jsonModal.style.display = 'none';
        imageModal.style.display = 'none';
        dropZone.style.display = 'flex';
        previewContainer.style.display = 'none';
        copyBase64Btn.disabled = true;

        // 处理图片并转换为Base64
        function handleImage(file) {
            if (!file.type.startsWith('image/')) {
                showToast('请选择图片文件', 'error');
                return;
            }

            const reader = new FileReader();
            reader.onload = function(e) {
                // 隐藏拖放区域
                dropZone.style.display = 'none';
                
                // 显示预览容器
                previewContainer.style.display = 'block';
                
                // 显示图片预览
                imagePreview.src = e.target.result;
                
                // 显示并设置Base64输出
                base64Output.value = e.target.result;
                
                // 启用复制按钮
                copyBase64Btn.disabled = false;
                
                // 显示成功提示
                showToast('图片处理成功');
            };
            
            reader.onerror = function() {
                showToast('读取图片失败', 'error');
            };
            
            reader.readAsDataURL(file);
        }

        // 重置图片上传
        function resetImageUpload() {
            dropZone.style.display = 'flex';
            previewContainer.style.display = 'none';
            imagePreview.src = '';
            base64Output.value = '';
            copyBase64Btn.disabled = true;
            imageInput.value = '';
            dropZone.classList.remove('dragover');
        }

        // 绑定事件监听器
        // 关闭按钮事件
        closeButtons.forEach(button => {
            button.addEventListener('click', function() {
                if (this.closest('#imageModal')) {
                    resetImageUpload();
                }
                jsonModal.style.display = 'none';
                imageModal.style.display = 'none';
            });
        });

        // 点击弹窗外部关闭
        window.addEventListener('click', function(event) {
            if (event.target === imageModal) {
                resetImageUpload();
                imageModal.style.display = 'none';
            }
            if (event.target === jsonModal) {
                jsonModal.style.display = 'none';
            }
        });

        // 打开图片工具弹窗
        imageTool.addEventListener('click', function() {
            resetImageUpload();
            imageModal.style.display = 'block';
        });

        // 选择图片按钮点击
        selectImageBtn.addEventListener('click', function() {
            imageInput.click();
        });

        // 监听文件选择
        imageInput.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                handleImage(this.files[0]);
            }
        });

        // 拖放功能
        dropZone.addEventListener('dragover', function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.add('dragover');
        });

        dropZone.addEventListener('dragleave', function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.remove('dragover');
        });

        dropZone.addEventListener('drop', function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.remove('dragover');
            
            const files = e.dataTransfer.files;
            if (files && files[0]) {
                handleImage(files[0]);
            }
        });

        // 复制Base64编码
        copyBase64Btn.addEventListener('click', function() {
            const text = base64Output.value;
            navigator.clipboard.writeText(text).then(() => {
                showToast('已复制到剪贴板');
            }).catch(err => {
                console.error('复制失败:', err);
                showToast('复制失败', 'error');
            });
        });

    } catch (error) {
        console.error('初始化失败:', error);
        // 显示错误信息
        const errorDiv = document.createElement('div');
        errorDiv.style.padding = '20px';
        errorDiv.style.color = 'red';
        errorDiv.textContent = '加载失败: ' + error.message;
        document.body.appendChild(errorDiv);
    }
}); 